Skip to content

Add no_std support#2

Open
bczhc wants to merge 6 commits intoceca69ec:mainfrom
bczhc:no_std_support
Open

Add no_std support#2
bczhc wants to merge 6 commits intoceca69ec:mainfrom
bczhc:no_std_support

Conversation

@bczhc
Copy link

@bczhc bczhc commented Nov 12, 2023

This PR adds no_std support and allow to run under no_std + alloc environment.

However there's one blocker: the RNG thing:

https://github.com/bczhc/bip38/blob/7265fa7b50b6b76faef2c206cf2205f0a9668c5c/src/lib.rs#L890-L899

In generate method, thread_rngs are used. But under no_std, there's no such RNG. Here should have some discussions. One solution is to pass an RngCore to generate, and allow the caller to choose the RNG.

I don't know if there's any method to generate nondeterministic random numbers under simple embedded systems. First we should grab a seed, and if the initial seed is deterministic, the further random numbers are all deterministic. It's impossible achieve an nondeterministic seed only from the software.

For example, here's an RNG implementation for Raspberry Pi Pico:

use rand::{Error, RngCore};
use rp_pico::pac::ROSC;

pub struct RoscRng;

impl RoscRng {
    #[inline]
    fn random_byte() -> u8 {
        let mut b = 0_u8;
        for i in 0..8 {
            let bits = unsafe { (*ROSC::PTR).randombit.read().bits() } as u8;
            b |= (bits & 0b1) << i;
        }
        b
    }
}

impl RngCore for RoscRng {
    fn next_u32(&mut self) -> u32 {
        let mut u = [0_u8; 4];
        self.fill_bytes(&mut u);
        u32::from_le_bytes(u)
    }

    fn next_u64(&mut self) -> u64 {
        let mut u = [0_u8; 8];
        self.fill_bytes(&mut u);
        u64::from_le_bytes(u)
    }

    fn fill_bytes(&mut self, dest: &mut [u8]) {
        for x in dest.iter_mut() {
            *x = Self::random_byte();
        }
    }

    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
        self.fill_bytes(dest);
        Ok(())
    }
}

@bczhc bczhc marked this pull request as draft November 12, 2023 09:48
@bczhc
Copy link
Author

bczhc commented Nov 12, 2023

I added generate_rng method for the use with no_std environment.

@bczhc bczhc marked this pull request as ready for review November 12, 2023 10:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant